const Common = require('./common');
const jwt = require('jsonwebtoken');
const util = require('util');
const verify = util.promisify(jwt.verify);
const axios = require('axios');

class User extends Common {
  constructor() {
    super('User');
    this.login = this.login.bind(this);
    this.checkUsername = this.checkUsername.bind(this);
    this.checkToken = this.checkToken.bind(this);
    this.getOpenId = this.getOpenId.bind(this);
    this.register = this.register.bind(this);
  }

  // 检查token是否已过期
  async checkToken(ctx) {
    console.log(ctx.user);
    ctx.body = ctx.user;
  }

  // 获取openId
  async getOpenId(ctx) {
    return new Promise((resolve, reject) => {
      let {
        code
      } = ctx.params;
      let appId = 'wx1a4e63fdc266444b';
      let AppSecret = '0f7f7ce015f01c8a6849a920fe1d460d';
      let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`
      axios.get(url).then(res => {
        console.log(res.data);
        if (res.data.openid) {
          resolve(res);
        } else {
          reject(res.data);
        }

      }).catch(err => {
        reject(err);
      })
    })
  }

  // 获取openId
  async getOpenId(ctx) {
    let {
      code
    } = ctx.params;
    let appId = 'wx1a4e63fdc266444b';
    let AppSecret = '0f7f7ce015f01c8a6849a920fe1d460d';
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`
    return axios.get(url);
  }

  /**
   * 用户名,密码注册
   * @param {*} ctx 
   */
  async register(ctx) {
    let {
      username,
      password
    } = ctx.params;

    let result = this.checkAttr(['username', 'password'], ctx);
    if (result) {
      ctx.body = result;
      return false;
    }
    try {
      result = await this.insert({
        username,
        password
      });
      ctx.body = this.successInfo(result);
    } catch (error) {
      ctx.body = this.errInfo(error);
    }
  }

  /**
   * 登出
   * @param {*} ctx 
   */
  async logout(ctx) {
    // 如何去销毁user对象
    ctx.body = {
      code: 666,
      msg: 'success'
    }
  }

  /**
   * 登录
   * 微信登录需要code
   * h5登录需要username
   */
  async login(ctx) {
    let {
      code,
      username
    } = ctx.params;

    let result;
    try {
      if (code) {
        result = await this.wxlogin(ctx);
      } else if (username) {
        result = await this.h5login(ctx);
      } else {
        ctx.body = {
          code: 602,
          msg: '缺少参数'
        }
        return false;
      }
      ctx.body = this.successInfo(result, '', 'user')
    } catch (error) {
      ctx.body = this.errInfo(error);
    }
  }

  /**
   * h5登录
   */
  async h5login(ctx) {
    return new Promise(async (resolve, reject) => {
      let result = this.checkAttr(['username', 'password'], ctx);
      if (result) {
        resolve(result);
      } else {
        try {
          let {
            username,
            password
          } = ctx.params;
          result = await this.find({
            username,
            password
          });

          if (result.length === 0) {
            result = await this.insert({
              username,
              password
            })
          } else {
            result = result[0];
          }
          let userId = result._id;
          let token = this.getToken({
            userId
          })
          resolve({
            token,
            username: result.username,
          })

        } catch (error) {
          reject(error);
        }
      }
    })
  }

  /**
   * 微信登录
   * @param {*} ctx 
   */
  async wxlogin(ctx) {
    return new Promise(async (resolve, reject) => {
      let result = this.checkAttr(['encryptedData', 'iv', 'code'], ctx);
      if (result) {
        ctx.body = result;
        return false;
      }
      try {
        let openData = await this.getOpenId(ctx);
        let openid = openData.data.openid;
        let query = {
          openid
        };
        let docs = await this.find(query);
        let user;
        // 找不到用户,说明用户还没创建
        if (docs.length === 0) {
          // 根据openid创建用户
          user = await this.insert({
            openid
          });
        } else {
          user = docs[0];
        }
        // token信息
        let userToken = {
          openid,
          userId: user._id
        }

        result = {
          token: this.getToken(userToken),
          _id: user._id
        }
        resolve(result);
        // ctx.body = this.successInfo(result, '', 'user');
      } catch (error) {
        // ctx.body = this.errInfo(error);
        reject(error);
      }
    })
  }

  /**
   * 添加token
   * @param {object} userToken
   */
  getToken(userToken) {
    let secret = 'shukan' // 指定密钥
    // 生成token
    let token = jwt.sign(userToken, secret, {
      expiresIn: '1000h'
    })
    return token;
  }

  async checkUsername(username) {
    return new Promise(async (resolve, reject) => {
      const query = {
        username
      }
      try {
        let docs = await this.find(query);
        if (docs.length > 0) {
          resolve({
            code: 111,
            msg: '用户名已存在'
          })
        } else {
          resolve(false);
        }
      } catch (error) {
        reject(error);
      }
    })
  }

}
module.exports = new User();
